package com.atguigu.webadmin.interceptor;

import com.atguigu.common.constant.LoginUser;
import com.atguigu.common.constant.LoginUserContext;
import com.atguigu.common.exception.SelfBusException;
import com.atguigu.common.result.ResultCodeEnum;
import com.atguigu.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName: AuthenticationInterceptor1
 * Package: com.atguigu.webadmin.interceptor
 * Description: 身份验证拦截器
 *
 * @Author 梅超凡
 * @Create 2024/11/15 21:03
 * @Version 1.0
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {
        //获取请求头中的token
        String token = request.getHeader("access_token");

        //判断token是否为空
        if (token == null) {
            //抛出未登录异常
            throw new SelfBusException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        } else {
            //解析token
            Claims claims = JwtUtil.parseToken(token);
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);
            LoginUserContext.setLoginUser(new LoginUser(userId, username));
        }
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request,
                                @NotNull HttpServletResponse response,
                                @NotNull Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
